<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  reqDeleteRoles,
  reqRoleList,
  reqRoleMenu,
  reqRolePermission,
  reqRoleSave,
  reqRoleUpdate,
} from "@/api/acl/role";
import {
  PermissionItem,
  PermissionList,
  RoleList,
  RoleListItem,
  RoleListParams,
} from "@/api/acl/role/type.ts";
import { ElMessage } from "element-plus";
import Role from "@/views/acl/role/index.vue";
import { RoleListResponseType, UserType } from "@/api/acl/user/type.ts";
import { reqUserRoleList } from "@/api/acl/user";
import useLayoutSettingStore from "@/store/modules/setting.ts";

let layoutSettingStore = useLayoutSettingStore();

// 定义查询参数
let queryParam = ref<RoleListParams>({
  pageNo: 1,
  pageSize: 3,
  roleName: "",
});

// 定义总条数
let total = ref(30);

// 角色列表
let roleList = ref<RoleList>([]);

// 添加角色的对话框是否显示
let addDialogVisible = ref(false);

// 添加角色的参数
let addParams = ref<RoleListItem>({
  roleName: "",
});

// 添加角色的表单
let addForm = ref<any>();

// 添加角色的标题
let addTitle = ref("添加角色");

// 权限抽屉是否显示
let permissionDrawer = ref(false);

// 权限抽屉的参数
let permissionDrawerParams = ref<RoleListItem>({
  id: 0,
  roleName: "",
});

// 用户拥有的角色列表
let userPermissionsResp = ref<PermissionList>([]);

// 用户拥有的角色id列表
let userPermissionIds = ref<number[]>([]);

// 权限树
let permissionTree = ref<any>();

// 分页大小改变时触发
const handleSizeChange = (val: number) => {
  queryParam.value.pageSize = val;
  getRoleList();
};

// 当前页改变时触发
const handleCurrentChange = (val: number) => {
  queryParam.value.pageNo = val;
  getRoleList();
};

// 获取角色列表
const getRoleList = async () => {
  let result = await reqRoleList(queryParam.value);
  if (result.code == 200) {
    roleList.value = result.data.records;
    total.value = result.data.total;
  }
};

// 搜索
const search = () => {
  getRoleList();
};

// 重置搜索
const resetSearch = () => {
  queryParam.value.roleName = "";
  getRoleList();
};

// 添加角色的对话框关闭前触发
const addHandleClose = () => {
  addDialogVisible.value = false;
};

// 添加角色dialog对话框打开
const openAddDialog = (row: RoleListItem | null) => {
  if (row) {
    addTitle.value = "编辑角色";
    addParams.value = JSON.parse(JSON.stringify(row)); // 深拷贝
  } else {
    addTitle.value = "添加角色";
  }
  addDialogVisible.value = true;
};

// 添加角色
const addRole = async () => {
  await addForm.value.validate(); // 验证表单
  let result = await reqRoleSave(addParams.value);
  if (result.code == 200) {
    addDialogVisible.value = false; // 关闭对话框
    ElMessage.success("添加角色成功");
    resetAddParams(); // 重置添加角色的参数
    getRoleList(); // 重新获取角色列表
  } else {
    ElMessage.error("添加角色失败");
  }
};

// 重置添加角色的参数
const resetAddParams = () => {
  addParams.value = {
    roleName: "",
  }; // 重置角色名称
  addForm.value.clearValidate(); // 清除验证
};

// 取消添加角色
const cancelAddParams = () => {
  resetAddParams(); // 重置添加角色的参数
  addDialogVisible.value = false; // 关闭对话框
};

// 编辑角色
const editRole = async (row: RoleListItem) => {
  let result = await reqRoleUpdate(row);
  if (result.code == 200) {
    ElMessage.success("编辑角色成功");
    addDialogVisible.value = false; // 关闭对话框
    getRoleList(); // 重新获取角色列表
  } else {
    ElMessage.error("编辑角色失败");
  }
};

// 添加或者更新角色
const addOrUpdateRole = () => {
  // 如果有id就是编辑角色，没有就是添加角色
  if (addParams.value.id) {
    editRole(addParams.value);
  } else {
    addRole();
  }
};

// 添加角色的验证规则
const addRules = {
  roleName: [
    {
      required: true,
      trigger: "blur",
      validator: (rule, value, callback) => {
        if (value == "") {
          callback(new Error("请输入角色名称"));
        } else if (value.length < 2 || value.length > 8) {
          callback(new Error("角色名称长度在2到8位之间"));
        } else {
          callback();
        }
      },
    },
  ],
};

// 打开权限抽屉
const openPermissionDrawer = async (row: RoleListItem) => {
  permissionDrawer.value = true; // 打开权限抽屉
  Object.assign(permissionDrawerParams.value, row); // 深拷贝
  let result = await reqRoleMenu(row.id as number); // 获取权限列表
  if (result.code == 200) {
    userPermissionsResp.value = result.data;
    filterSelectArr(userPermissionsResp.value, userPermissionIds.value); // 递归获取用户拥有的权限id
  }
};

// 递归获取用户拥有的权限id
// 如果有children就递归，
// 如果没有children就判断是否选中，选中就push到userPermissionIds
const filterSelectArr = (
  userPermissionsResp: PermissionList,
  Arr: number[],
) => {
  userPermissionsResp.forEach((item: PermissionItem) => {
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, Arr);
    } else {
      if (item.select) {
        Arr.push(item.id as number);
      }
    }
  });
};

// 权限抽屉提交
const permissionsSubmit = async () => {
  let checkedKeys = permissionTree.value.getCheckedKeys(); // 获取选中的权限id
  let halfCheckedKeys = permissionTree.value.getHalfCheckedKeys(); // 获取半选中的权限id
  let permissionIds = checkedKeys.concat(halfCheckedKeys); // 合并选中和半选中的权限id
  let params = {
    roleId: permissionDrawerParams.value.id,
    permissionId: permissionIds,
  };

  let result = await reqRolePermission(params.roleId, params.permissionId);
  if (result.code == 200) {
    ElMessage.success("设置权限成功");
  } else {
    ElMessage.error("设置权限失败");
  }

  permissionDrawer.value = false;

  layoutSettingStore.refresh = !layoutSettingStore.refresh; // 刷新页面
};

// 权限抽屉取消
const permissionsCancel = () => {
  permissionDrawer.value = false;
};

// 删除角色
const deleteRole = async (row: RoleListItem) => {
  let idList = [row.id as number];
  let result = await reqDeleteRoles(idList);
  if (result.code == 200) {
    ElMessage.success("删除角色成功");
    getRoleList();
  } else {
    ElMessage.error("删除角色失败");
  }
};

onMounted(() => {
  getRoleList();
});

defineOptions({
  name: "Role",
});

const defaultProps = {
  children: "children",
  label: "name",
};
</script>

<template>
  <!-- 搜索框 -->
  <el-card>
    <el-form inline class="head-form">
      <el-form-item label="角色名称">
        <el-input
          placeholder="请输入角色名称"
          v-model="queryParam.roleName"
        ></el-input>
      </el-form-item>
      <el-form-item class="head-btn">
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 表格 -->
  <el-card class="role-table">
    <el-button
      type="primary"
      size="mini"
      class="table-btn"
      @click="openAddDialog(null)"
      >添加角色
    </el-button>
    <el-table border :data="roleList">
      <el-table-column
        align="center"
        type="selection"
        width="80px"
      ></el-table-column>
      <el-table-column
        align="center"
        label="序号"
        type="index"
        width="80px"
      ></el-table-column>
      <el-table-column
        align="center"
        label="角色名称"
        prop="roleName"
        show-overflow-tooltip
        width="200px"
      ></el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        width="200px"
      ></el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <el-button
            type="primary"
            icon="plus"
            size="mini"
            @click="openPermissionDrawer(row)"
            >分配权限
          </el-button>
          <el-button
            type="success"
            icon="edit"
            size="mini"
            @click="openAddDialog(row)"
            >编辑
          </el-button>
          <el-popconfirm
            title="确定删除该角色吗？"
            confirmButtonText="确定"
            cancelButtonText="取消"
            icon="el-icon-question"
            width="200px"
            @confirm="deleteRole(row)"
          >
            <template #reference>
              <el-button type="danger" icon="delete" size="mini">
                删除角色
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--  分页器  -->
    <el-pagination
      v-model:current-page="queryParam.pageNo"
      v-model:page-size="queryParam.pageSize"
      :page-sizes="[1, 3, 5, 10]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    >
    </el-pagination>

    <el-dialog
      :title="addTitle"
      v-model="addDialogVisible"
      width="30%"
      :before-close="addHandleClose"
    >
      <template #default>
        <el-form ref="addForm" :rules="addRules" :model="addParams">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addParams.roleName"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="cancelAddParams">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateRole">确 定</el-button>
      </template>
    </el-dialog>
  </el-card>

  <el-drawer title="设置员工权限" v-model="permissionDrawer">
    <template #default>
      <el-form v-model="permissionDrawerParams">
        <el-form-item label="角色名">
          <el-input
            v-model="permissionDrawerParams.roleName"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="权限列表">
          <el-tree
            :data="userPermissionsResp"
            show-checkbox
            node-key="id"
            :default-expanded-all="true"
            :default-checked-keys="userPermissionIds"
            :props="defaultProps"
            ref="permissionTree"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="permissionsSubmit">确 定</el-button>
      <el-button @click="permissionsCancel">取 消</el-button>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">
.head-form {
  display: flex;
  justify-content: space-between;
  height: 20px;
  margin-bottom: 10px;
}

.head-btn {
  display: flex;
}

.role-table {
  margin-top: 10px;
}

.table-btn {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
